﻿using CameraClient.CForm.CameraF;
using Edge.Repository.Model.CameraSys;
using Edge.Repository.Model.CameraSys.CDal;
using HYRN.Common.ConvertUtilities;
using HZH_Controls;
using LibVLCSharp.Shared;
using Oliving.Common.LogHelper;
using Oliving.FormCommon.Oliving.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;

using System.Windows.Forms;
using Vlc.DotNet.Core.Interops;
using VideoTrack = LibVLCSharp.Shared.VideoTrack;



namespace WindowsFormsApp4.EdgeVlc
{


    public delegate void CustomEventHandler(object sender, EventArgs e);
    public partial class EdgeVlcUc : UserControl
    {
        public event CustomEventHandler CustomEvent;


        // 触发事件的方法
        public void RaiseCustomEvent()
        {
            // 检查是否有注册监听器
            if (CustomEvent != null)
            {
                // 触发事件，传递this（发送者）和EventArgs.Empty（事件数据）
                CustomEvent(this, EventArgs.Empty);
            }
        }

        int xiaoZhuenWenDu = 50;

        public CameraConfigModel CameraConfig;
        public EdgeVlcUc(CameraConfigModel cameraConfigModel)
        {
            InitializeComponent();
            CameraConfig = cameraConfigModel;

            if (string.IsNullOrEmpty(cameraConfigModel.Attribute1))
            {
                xiaoZhuenWenDu = 0;
            }
            else
            {
                xiaoZhuenWenDu = cameraConfigModel.Attribute1.ObjToInt();
                if (xiaoZhuenWenDu == 0) { xiaoZhuenWenDu = 0; }
            }

            #region LibVLC

            _libVlc = new LibVLC();


            _mediaPlayer1 = new MediaPlayer(_libVlc)
            {
                Volume = 0, //静音
                EnableHardwareDecoding = isMainControl,
                //硬件加速
                // VideoFilter = "format=gray" 
            };



            {

                // 订阅事件
                _mediaPlayer1.Stopped += Player_Stopped;
                _mediaPlayer1.EncounteredError += Player_EncounteredError;
                _mediaPlayer1.Buffering += Player_Buffering;

                //_mediaPlayer.Buffering += OnBuffering;
                //_mediaPlayer.StateChanged += OnStateChanged;

            }


            videoViewMain.MediaPlayer = _mediaPlayer1;

            Load += OnLoad;
            HandleDestroyed += OnHandleDestroyed;

            #endregion

            ShowDto(cameraConfigModel);


        }




        #region 播放器 监听事件
        public event Action OnConnectionLost;
        public event Action<string> OnStatusChanged;

        private void Player_Buffering(object sender, MediaPlayerBufferingEventArgs e)
        {
            //OnStatusChanged?.Invoke($"缓冲: {e.Cache}%"); 
            //if (e.Cache < 5 && _mediaPlayer1.State == VLCState.Playing)
            //{
            //    OnConnectionLost?.Invoke();
            //}


            if (e.Cache < 10)
            {
                //Console.WriteLine("网络不稳定，缓冲不足");
            }
            else if (e.Cache > 90)
            {
                //Console.WriteLine("网络恢复，缓冲充足");
                if (_mediaPlayer1.State == VLCState.Paused)
                {
                    _mediaPlayer1.Play(); // 自动恢复播放
                }
            }


        }

        private void Player_EncounteredError(object sender, EventArgs e)
        {
            OnStatusChanged?.Invoke("播放错误");
            OnConnectionLost?.Invoke();
        }

        private void Player_Stopped(object sender, EventArgs e)
        {
            OnStatusChanged?.Invoke("播放停止");
        }
        // =================================================================





        #endregion

        public void ShowDto(CameraConfigModel cameraConfigModel)
        {
            groupBox1.Text = cameraConfigModel.Name;
        }




        MediaPlayer _mediaPlayer1;
        LibVLC _libVlc;

        bool isMainControl = true;


        private void OnLoad(object sender, EventArgs e)
        {
            DoubleBuffered = true;
            videoViewMain.Enabled = false;




        }

        private void OnHandleDestroyed(object sender, EventArgs args)
        {
            _mediaPlayer1.Stop();
            _mediaPlayer1.Dispose();

            _libVlc.Dispose();
        }


        string myUrl = "rtsp://admin:cjkj1234@192.168.1.50:554/streaming/Channels/101?transportmode=unicast";


        public bool isPlay = false;

        public void play()
        {
            isPlay = true;
            var options = new[] { ":network-caching=1000", ":rtsp-tcp", ":no-audio" };
            var options1 = new[]
                    {
                    "no-audio",
                    "file-caching=300",
                    "live-capture-caching=300",
                    "disc-caching-caching=300",
                    "network-caching=333",
                    "live-caching=300",
                     isMainControl   ? "avcodec-hw=any" : "" //硬解码
                };

            var options2 = new[]
                 {
                    "no-audio",
                    "file-caching=2000",
                    "live-capture-caching=2000",
                    "disc-caching-caching=2000",
                    "network-caching=2000",
                    "live-caching=2000",
                     isMainControl   ? "avcodec-hw=any" : "" //硬解码
                };



            if (_mediaPlayer1 != null)
            {
                if (!_mediaPlayer1.IsPlaying)
                {

                    string myUrlA = "http://localhost:9999/redis.mp4"; // "rtsp://192.168.0.102:8554/livestream";

                    myUrlA = CameraConfig.Source;

                    try
                    {
                        using (var media = new Media(_libVlc, new Uri(myUrlA), options))
                        {
                            _mediaPlayer1.Play(media);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            }
        }


        public void stop()
        {
            isPlay = false;

            if (_mediaPlayer1.IsPlaying)
            {
                _mediaPlayer1.Stop(); groupBox1.Text = CameraConfig.Name;
            }

        }



        // 创建Random类的实例
        Random random = new Random();

        int showWendu_Main = 0;


        DateTime logTime = DateTime.MinValue;


        public void SetForm_Wendu()
        {


            // int huidu = random.Next(210, 255);
            // int showWendu = CameraConfig.MinWenDu + Convert.ToInt32(huiduOne * huidu);

            int showWendu = random.Next(CameraConfig.MaxWenDu - 50, CameraConfig.MaxWenDu);
            showWendu = showWendu - xiaoZhuenWenDu;
            if (showWendu_Main == showWendu)
            {

                showWendu = showWendu - 1;
                showWendu_Main = showWendu;
            }
            this.Invoke(new EventHandler(delegate
            {
                groupBox1.Text = CameraConfig.Name + " : " + showWendu + "℃";
            }));

            DateTime itemTime = DateTime.Now.ObjToFullTimeHasmm();
            if (logTime == DateTime.MinValue || logTime != itemTime)
            {
                logTime = itemTime;
                CameraDataModel cameraData = new CameraDataModel()
                {
                    CreateTime = logTime,
                    HuiDu = 0,
                    Pid = CameraConfig.Id,
                    WenDu = showWendu,
                };

                Insert(cameraData);
            }




        }


        public void CalcHuiDu()
        {
            decimal huiduOne = ((CameraConfig.MaxWenDu - CameraConfig.MinWenDu).ObjToDecimal() / 255).ObjToDecimal();
            if (huiduOne == 0) { huiduOne = 1; }

            while (true)
            {
                Thread.Sleep(1 * 1000);

                if (isPlay)
                {
                    bool NoVideoSignal = CheckNoVideoSignal(_mediaPlayer1);

                    if (NoVideoSignal)
                    {
                        //   return true;(" 海康无信号画面 ");

                        this.Invoke(new EventHandler(delegate
                        {
                            groupBox1.Text = CameraConfig.Name;
                        }));

                    }
                    else
                    {
                        bool urlExists = true; // CheckUrlExists(CameraConfig.Source);

                        if (urlExists && _mediaPlayer1.IsPlaying)
                        {
                            SetForm_Wendu();

                        }
                        else
                        {
                            this.Invoke(new EventHandler(delegate
                            {
                                groupBox1.Text = CameraConfig.Name;
                            }));

                            play();
                        }
                    }


                }
                else
                {
                    this.Invoke(new EventHandler(delegate
                    {
                        groupBox1.Text = CameraConfig.Name;
                    }));
                }

            }

        }



        public void ThreadHuiDu()
        {
            Thread thread = new Thread(new ThreadStart(CalcHuiDu));
            thread.Start();
        }

        private void EdgeVlcUc_Load(object sender, EventArgs e)
        {
            ThreadHuiDu();
        }
        int showTime = 100;

        public void Insert(CameraDataModel cameraData)
        {
            CameraDataService cameraDal = new CameraDataService();
            try
            {
                Thread.Sleep(100);
                cameraDal.Add(cameraData);
            }
            catch (Exception ee)
            {
                NLogger.Default.Debug("Insert", ee.ToString());

            }
        }


        #region  功能按钮


        private void 曲线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 曲线 


            FormChart form = new FormChart(CameraConfig);

            if (form.ShowDialog() == DialogResult.OK)
            {
                RaiseCustomEvent();
            }
        }

        private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormCameraEdit form = new FormCameraEdit(CameraConfig.Id);

            if (form.ShowDialog() == DialogResult.OK)
            {
                RaiseCustomEvent();
            }
        }

        private void 停止ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "jpg文件 | *.jpg";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    //  _mediaPlayer.Fullscreen = true;
                    _mediaPlayer1.TakeSnapshot(
                        1,
                        sfd.FileName,
                        (uint)videoViewMain.Width,
                        (uint)videoViewMain.Height);

                }
            }
            stop();
        }

        private void 启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            play();
        }

        private void 全屏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //videoViewMain_Click(null, null);
            //if (false)
            {
                // 全屏 
                FormCameraFull form = new FormCameraFull(CameraConfig);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    RaiseCustomEvent();
                }
            }
        }


        #endregion



        #region 视频窗体的


        private void HandleMouseWheel(MouseEventArgs e)
        {
            if (e.Delta > 0)
            {
                // 向上滚动
                // MessageBox.Show("向上滚动");
                sizeBaiFenBi = sizeBaiFenBi + 5;
            }
            else if (e.Delta < 0)
            {
                // 向下滚动
                // MessageBox.Show("向下滚动");
                sizeBaiFenBi = sizeBaiFenBi - 5;
            }
            ChangeView(sizeBaiFenBi);
        }

        int sizeBaiFenBi = 100;
        public void ChangeView(int paraSizeBaiFenBi)
        {
            if (is放大与移动视频展示)
            {
                decimal bfb = paraSizeBaiFenBi.ToDecimal() / 100;

                Size size = DefControlUtils.CalculateGroupBoxSize(groupBox1);
                panel3.Width = (size.Width * (bfb)).ObjToInt();
                panel3.Height = (size.Height * (bfb)).ObjToInt();
            }

        }



        Point downPoint;




        bool is放大与移动视频展示 = false;



        private void panel3_MouseDown(object sender, MouseEventArgs e)
        {

            downPoint = new Point(e.X, e.Y);
        }

        private void panel3_MouseMove(object sender, MouseEventArgs e)
        {
            if (is放大与移动视频展示)
            {
                if (e.Button == MouseButtons.Left)
                {
                    panel3.Location = new Point(
                      panel3.Location.X + e.X - downPoint.X,
                      panel3.Location.Y + e.Y - downPoint.Y);
                }
            }

        }


        #endregion




        // ============================================================


        // 检查无视频信号的方法
        public bool CheckNoVideoSignal(MediaPlayer player)
        {
            try
            {
                LibVLCSharp.Shared.MediaTrack track = player.Media.Tracks.FirstOrDefault(t => t.TrackType == TrackType.Video);
                if (track.Data is MediaTrackData)
                {
                    // 处理视频轨道
                    MediaTrackData videoTrack = (MediaTrackData)track.Data;


                    //Console.WriteLine($"找到视频轨道: {track.Data.Video.Width}x{track.Data.Video.Height}"); 
                    //Console.WriteLine($"找到视频轨道: {player.Media.State}");

                    // 海康无信号检测逻辑
                    if (IsHikvisionNoSignal(videoTrack.Video))
                    {
                        //Console.WriteLine("海康设备无视频信号");
                        return true;
                    }
                    else
                    {
                        //Console.WriteLine("正常视频信号"); 
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"获取视频轨道出错: {ex.Message}");
                return true;
            }
            return true;
        }

        // 海康无信号检测方法
        public bool IsHikvisionNoSignal(VideoTrack track)
        {
            int myWidth = track.Width.ObjToInt();
            int myHeight = track.Height.ObjToInt();

            int hasData = GetData_WuShiPinXinHao().Count(F => F.Width == myWidth && F.Height == myHeight);

            if (hasData > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }



        /// <summary>
        ///  无视频信号 的分辨率
        /// </summary>
        public List<Size> GetData_WuShiPinXinHao()
        {

            List<Size> data = new List<Size>();

            data.Add(new Size(352, 240));
            data.Add(new Size(640, 480));
            data.Add(new Size(704, 480));
            data.Add(new Size(960, 480));
            data.Add(new Size(1280, 720));

            return data;
        }

    }
}
